import axios from 'axios'
import router from '../router'
let http = axios.create({
  timeout: 2000000,
  baseURL: '/api'
})
/* 二次封装Ajax */
  http.interceptors.request.use(req => {
    let token = sessionStorage.getItem('token')
    // token && (req.headers['Authorization'] = `Bearer ${token}`)
    if(token){
      req.headers['Authorization'] = `Bearer ${token}`
    }
    return req
  })
  http.interceptors.response.use(resp => {
    resp.data.token && sessionStorage.setItem('token', resp.data.token)
    return resp
  }, error => {
    let _resp = error.response
    switch (_resp.status) {
      case 401:
        sessionStorage.removeItem('token')
        sessionStorage.removeItem('user')
        alert('身份已经过期,请重新登录')
        return router.push('/login')
      case 500:
        alert('服务器报错')
    }
    return Promise.reject(error.response.data)
  })


export default http